/*
    * @module:views/budget/investBudget/reckoningList
    * @author:zengfx
    * @date:2020-12-16
    * 投资完成导入
*/
<template>
  <div class="reckoningList_container">
    <div>
      <el-form :inline="true" :model="form" label-width="60px">
        <el-form-item label="区域">
          <dx-cascader :area_id.sync="form.areaId" :maxLevel="2" />
        </el-form-item>
        <el-form-item label="文件名">
          <el-input size="mini" v-model="form.fileName" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button size="mini" type="primary" @click="handle_search()">查询</el-button>
          <el-button size="mini" @click="template_download()">模板下载</el-button>
          <el-button size="mini" type="orange" @click="dialogVisible = true;fileList = []">导入</el-button>
        </el-form-item>
      </el-form>

      <div class="tableBox">
        <el-table height="73vh" id="table" size="mini" :header-cell-style="{ background: '#eef1f6' }" :data="tableData" v-loading="tableLoading" style="width: 100%;" border>
          <el-table-column width="120" label="区域" prop="areaName"></el-table-column>
          <el-table-column label="文件名" prop="fileName"></el-table-column>
          <el-table-column width="140" label="导入人" prop="userName"></el-table-column>
          <el-table-column width="140" label="导入时间" prop="importDate" :formatter="dateFormatter"></el-table-column>
          <el-table-column width="240" label="操作">
            <template slot-scope="scope">
              <el-button type="text" size="mini" @click="handle_check(scope.row)">查看</el-button>
              <el-button type="text" size="mini" @click="handle_delete(scope.row.fileId)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <el-dialog title="导入文件" append-to-body :visible.sync="dialogVisible" width="30%">
      <el-form :model="importForm" ref="importForm">
        <el-form-item label="预算年份" :label-width="formLabelWidth" prop="description">
          <el-date-picker size="mini" v-model="importForm.acctYear" value-format="yyyy" type="year" placeholder="选择年"></el-date-picker>
        </el-form-item>
        <el-form-item label="上传文件" :label-width="formLabelWidth">
          <el-upload :limit="1" accept=".xls, .xlsx" class="avatar-uploader" :auto-upload="false" :file-list="fileList" :on-change="changeFile" action>
            <el-button size="mini" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogVisible = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="handle_import">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { $budgetAPI } from "@/api/";
import { getSessionStorage } from "@/common/js/storage";
import { getCookie } from "@/common/js/cookie";
import prefixAPI from "@/api/prefixAPI";
import { _formatTime } from "@/utils/common";

export default {
  name: "reckoning-tab1",
  data() {
    return {
      form: {
        areaId: "",
        fileName: "",
      },
      tableData: [],
      accountInfo: null,
      tableLoading: false,
      dialogVisible: false,
      importForm: { acctYear: "" },
      fileList: [],
      param: "",
      formLabelWidth: "80px",
      activeName: "first",
    };
  },
  computed: {
    params() {
      let obj = {
        areaId: this.form.areaId,
        token: getCookie("token"),
      };
      return obj;
    },
  },
  created() {
    this.accountInfo = JSON.parse(getSessionStorage("accountInfo"));
    this.form.areaId = this.accountInfo.areaId;
  },
  mounted() {},
  methods: {
    init() {
      // this.getBudgetClearMaxYear();
      this.getBudgetClearDataList();
    },
    dateFormatter(row, column) {
      let datetime = row.importDate;
      if (datetime) {
        datetime = new Date(datetime);
        let y = datetime.getFullYear() + "-";
        let mon = datetime.getMonth() + 1 + "-";
        let d = datetime.getDate();
        return y + mon + d;
      }
      return "";
    },
    // 模板下载
    template_download() {
      let token = getCookie("token");
      let areaId = this.form.areaId;
      // 根据不同模式切换不同的路径
      if (process.env.NODE_ENV == "development") {
        window.location.href =
          prefixAPI.loc +
          "/api/incomeBudget/budgetClearTemplateDownLoad?areaId=" +
          areaId +
          "&token=" +
          token;
      } else if (process.env.NODE_ENV == "production") {
        window.location.href =
          prefixAPI.hp +
          "/api/incomeBudget/budgetClearTemplateDownLoad?areaId=" +
          areaId +
          "&token=" +
          token;
      }
      // $budgetAPI.releaseTemplateDownLoad(this.form, res => {
      //     if (res.code == 0) {
      //     }
      // });
    },
    progress(event, file, fileList) {
      this.loading = this.$loading({
        lock: true,
        text: "正在导入",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
    },
    // 批量导入上传文件传递数据
    changeFile(file, fileList) {
      this.fileList = fileList;
      this.param = new FormData();
      this.param.append("file", file.raw);
    },
    getBudgetClearMaxYear() {
      $budgetAPI.getBudgetClearMaxYear(
        {
          areaId: this.form.areaId,
        },
        (res) => {
          if (res.code == 0) {
            this.importForm.acctYear = res.content.MaxacctMonth.substr(0, 4);
          }
        },
        (err) => {
          console.log(err);
        }
      );
    },
    handle_import() {
      this.$refs["importForm"].validate((valid) => {
        if (valid) {
          if (this.fileList.length == 0) {
            this.$message({
              message: "请选择需要上传的文件",
              type: "warning",
            });
            return false;
          }
          this.param.append("token", getCookie("token"));
          this.param.append("areaId", this.form.areaId);
          this.param.append("testYear", this.importForm.acctYear);
          $budgetAPI.importBudgetClearData(
            this.param,
            (res) => {
              if (res.code == 0) {
                this.$message({
                  message: "导入成功",
                  type: "success",
                });
                this.getBudgetClearDataList();
              } else {
                this.$message.error(res.message);
              }
              this.dialogVisible = false;
            },
            (err) => {
              console.log(err);
              this.dialogVisible = false;
            }
          );
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //导入成功的回调
    importTarget(response, file, fileList) {
      this.alertError(response);
      this.loading.close();
      if (response.code == 0) {
        this.$message({
          type: "success",
          message: "导入成功",
        });
        this.getBudgetClearDataList();
      }
    },
    errorUpload(err, file, fileList) {
      console.log(err);
      this.loading.close();
    },
    handle_search() {
      this.getBudgetClearDataList();
    },
    handle_check(row) {
      let query = {
        fileId: row.fileId,
        areaId: row.areaId,
        areaName: row.areaName,
        acctMonth: this.moment(row.importDate).format("yyyyMM"),
      };

      let strEncode = encodeURI(JSON.stringify(query));
      let urlEncode = window.btoa(strEncode);

      this.$router.push({
        path: "/budget/budgetReckoning",
        query: {
          url: urlEncode,
        },
      });
    },
    handle_delete(id) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          $budgetAPI.deleteBudgetClearData(
            { fileId: id },
            (res) => {
              if (res.code == 0) {
                this.$message({
                  type: "success",
                  message: "删除成功!",
                });
                this.getBudgetClearDataList();
              } else {
                this.$message.error(res.message);
              }
            },
            (err) => {
              console.log(err);
            }
          );
        })
        .catch((error) => {
          console.log(error);
        });
    },
    getBudgetClearDataList() {
      this.tableLoading = true;
      $budgetAPI.getBudgetClearDataList(
        this.form,
        (res) => {
          if (res.code == 0) {
            this.tableData = res.content;
          }
          this.tableLoading = false;
        },
        (err) => {
          this.tableLoading = false;
        }
      );
    },
  },
};
</script>

<style lang="scss" scoped>
/deep/ .el-form--inline .el-form-item.fr {
  .el-form-item__content {
    width: 169px;
  }
}
.downloadBtn {
  margin-top: 6px;
  margin-right: 10px;
}
</style>